#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "head_2.h"

#define N 64

sendEnv envMsg;

void *handler(void * arg){
	int sockfd = (int)arg;

	for(;;){
		envMsg.head[0] = 's';
		envMsg.head[1] = 't';
		envMsg.head[2] = ':';
		envMsg.type = 'e';
		envMsg.snum = 1;
		envMsg.temp[0] = (uint8_t )(random()%30);
		envMsg.temp[1] = 0;
		envMsg.hum[0] =(uint8_t)random()%50;
		envMsg.hum[1] = 0;
		envMsg.ill = (uint8_t)random()%20;
		envMsg.x = (uint8_t)random()%10;
		envMsg.y = (uint8_t)random()%30;
		envMsg.z = (uint32_t)random()%50;
		envMsg.bet = (uint32_t)random()%33/10;  
		envMsg.adc = (uint32_t)random()%10; 

		usleep(10000);
		send(sockfd,&envMsg,sizeof(sendEnv),0);
	}

	close(sockfd);
	pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
	int listenfd, sockfd;
	struct sockaddr_in myaddr;

	if (argc < 3)
	{
		printf("Usage : %s <ip> <port>\n", argv[0]);
		exit(-1);
	}


	//创建服务器socket
	listenfd = socket(PF_INET, SOCK_STREAM, 0);
	if(listenfd < 0){
		perror("fail to socket");
		exit(-1);
	}
	bzero(&myaddr, sizeof(myaddr));
	myaddr.sin_family = PF_INET;
	myaddr.sin_port = htons(atoi(argv[2]));
	myaddr.sin_addr.s_addr = inet_addr(argv[1]);
	if (bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) < 0)
	{
		perror("fail to bind");
		exit(-1);
	}

	// XXX int listen(int sockfd, int backlog);
	if (listen(listenfd, 5) < 0)
	{
		perror("fail to listen");
		exit(-1);
	}

	//接受客户端请求，创建子线程
	while(1){
		if((sockfd = accept(listenfd, NULL, NULL)) < 0){
			perror("fail to accept");
			exit(-1);
		}

		pthread_t child_pthread;
		if(pthread_create(&child_pthread, NULL, handler,(void *)sockfd) < 0)
		{
			perror("pthread_create");
			exit(1);
		}
	}
}

